package com.wisewin.circle.service;

import com.wisewin.circle.config.dto.ResultDTO;
import com.wisewin.circle.config.dto.ResultDTOBuilder;
import com.wisewin.circle.dao.TrendDAO;
import com.wisewin.circle.dao.TrendHeartDAO;
import com.wisewin.circle.entity.db.TrendDO;
import com.wisewin.circle.entity.db.TrendHeartDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class TrendHeartService {

    @Autowired
    private TrendDAO trendDAO;
    @Autowired
    private TrendHeartDAO trendHeartDAO;

    // 添加动态点赞收藏
    public ResultDTO addTrendHeart(TrendHeartDO trendHeartDO) {
        if (trendHeartDO.getTrendId() == null) {
            return ResultDTOBuilder.failure("1", "参数有误", null);
        }
        TrendDO trendDO = trendDAO.queryTrendById(trendHeartDO.getTrendId());
        if (trendDO == null) {
            return ResultDTOBuilder.failure("1", "当前动态不存在", null);
        }
        // 判断是否已点赞
        TrendHeartDO trendHeartOld = trendHeartDAO.queryTrendHeartById(trendHeartDO.getUserId(), trendHeartDO.getTrendId());
        if (trendHeartOld != null) {
            return ResultDTOBuilder.failure("1", "已点赞收藏", null);
        }
        // 添加动态点赞收藏
        trendHeartDAO.insert(trendHeartDO);
        // 修改动态点赞收藏数量
        trendDAO.updateHeartNum(trendHeartDO.getTrendId());
        return ResultDTOBuilder.success(trendHeartDO);
    }

    // 取消点赞收藏
    public ResultDTO cancleTrendHeart(TrendHeartDO trendHeartDO) {
        if (trendHeartDO.getTrendId() == null) {
            return ResultDTOBuilder.failure("1", "参数有误", null);
        }
        TrendDO trendDO = trendDAO.queryTrendById(trendHeartDO.getTrendId());
        if (trendDO == null) {
            return ResultDTOBuilder.failure("1", "当前动态不存在", null);
        }
        // 判断是否已点赞
        TrendHeartDO trendHeartOld = trendHeartDAO.queryTrendHeartById(trendHeartDO.getUserId(), trendHeartDO.getTrendId());
        if (trendHeartOld == null) {
            return ResultDTOBuilder.failure("1", "未点赞收藏", null);
        }
        // 添加动态点赞收藏
        trendHeartDAO.delete(trendHeartDO.getUserId(), trendHeartDO.getTrendId());
        // 修改动态点赞收藏数量
        trendDAO.cancleHeartNum(trendHeartDO.getTrendId());
        return ResultDTOBuilder.success(trendHeartDO);
    }
}
